import type { ServiceProviderOAuthConfig } from './oauth-config-types'
import { createDefaultOAuthConfig } from './oauth-config-templates'

// Mock OAuth配置数据
const mockOAuthConfigs: ServiceProviderOAuthConfig[] = [
  {
    id: 'OAUTH_001',
    providerId: 'SP1752154718336',
    providerName: '火金科技',
    wechatOAuth: {
      mp: {
        appId: 'wx1234567890abcdef',
        appSecret: 'abcdef1234567890abcdef1234567890',
        token: 'your_token_here',
        encodingAesKey: 'abcdefghijklmnopqrstuvwxyz1234567890ABCDEFG',
        enabled: true
      },
      miniapp: {
        appId: 'wx0987654321fedcba',
        appSecret: 'fedcba0987654321fedcba0987654321',
        token: 'your_miniapp_token',
        encodingAesKey: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefg',
        enabled: true
      },
      open: {
        appId: 'wx1111222233334444',
        appSecret: '1111222233334444555566667777888899990000',
        enabled: false
      }
    },
    alipayOAuth: {
      app: {
        appId: '2021000000000000',
        privateKey: 'MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC9QFi67KZ41+3Q...',
        alipayPublicKey: 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA9QFi67KZ41+3Q...',
        enabled: true
      },
      oauth: {
        scope: ['auth_user'],
        redirectUri: 'https://api.example.com/oauth/alipay/callback',
        enabled: true
      }
    },
    commonConfig: {
      environment: 'SANDBOX',
      callbackDomain: 'https://api.example.com',
      encryptionKey: 'your_encryption_key_here'
    },
    status: 'ACTIVE',
    createdTime: '2024-01-15 10:00:00',
    updatedTime: '2024-01-20 15:30:00'
  },
  {
    id: 'OAUTH_002',
    providerId: 'SP1752154718337',
    providerName: '田园网络',
    wechatOAuth: {
      mp: {
        appId: 'wx2222333344445555',
        appSecret: '2222333344445555666677778888999900001111',
        token: 'zhifutong_token',
        encodingAesKey: 'zhifutong1234567890ABCDEFGHIJKLMNOPQRSTUVWX',
        enabled: true
      },
      miniapp: {
        appId: 'wx5555444433332222',
        appSecret: '5555444433332222111100009999888877776666',
        token: 'zhifutong_miniapp_token',
        encodingAesKey: 'ZHIFUTONG1234567890abcdefghijklmnopqrstuvwx',
        enabled: true
      },
      open: {
        appId: 'wx6666777788889999',
        appSecret: '6666777788889999000011112222333344445555',
        enabled: true
      }
    },
    alipayOAuth: {
      app: {
        appId: '2021000000000001',
        privateKey: 'MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC8QFi67KZ41+3Q...',
        alipayPublicKey: 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA8QFi67KZ41+3Q...',
        enabled: true
      },
      oauth: {
        scope: ['auth_user', 'auth_base'],
        redirectUri: 'https://tianyuan.com/oauth/alipay/callback',
        enabled: true
      }
    },
    commonConfig: {
      environment: 'PRODUCTION',
      callbackDomain: 'https://tianyuan.com',
      encryptionKey: 'tianyuan_encryption_key'
    },
    status: 'ACTIVE',
    createdTime: '2024-01-10 09:00:00',
    updatedTime: '2024-01-25 14:20:00'
  },
  {
    id: 'OAUTH_003',
    providerId: 'SP1752154718338',
    providerName: '蓝图引擎',
    wechatOAuth: {
      mp: {
        appId: 'wx3333444455556666',
        appSecret: '3333444455556666777788889999000011112222',
        token: 'lantu_token',
        encodingAesKey: 'lantu1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ',
        enabled: false
      },
      miniapp: {
        appId: 'wx6666555544443333',
        appSecret: '6666555544443333222211110000999988887777',
        token: 'lantu_miniapp_token',
        encodingAesKey: 'LANTU1234567890abcdefghijklmnopqrstuvwxyz',
        enabled: false
      },
      open: {
        appId: 'wx7777888899990000',
        appSecret: '7777888899990000111122223333444455556666',
        enabled: false
      }
    },
    alipayOAuth: {
      app: {
        appId: '2021000000000002',
        privateKey: '',
        alipayPublicKey: '',
        enabled: false
      },
      oauth: {
        scope: ['auth_base'],
        redirectUri: 'https://lantu.com/oauth/alipay/callback',
        enabled: false
      }
    },
    commonConfig: {
      environment: 'SANDBOX',
      callbackDomain: 'https://lantu.com',
      encryptionKey: ''
    },
    status: 'INACTIVE',
    createdTime: '2024-01-12 11:00:00',
    updatedTime: '2024-01-12 11:00:00'
  }
]

// 模拟API响应延迟
const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))

// 获取服务商OAuth配置
export async function mockGetProviderOAuthConfig(providerId: string): Promise<{
  success: boolean
  data: ServiceProviderOAuthConfig | null
  message: string
}> {
  await delay(500)

  const config = mockOAuthConfigs.find(c => c.providerId === providerId)

  if (config) {
    return {
      success: true,
      data: config,
      message: '获取OAuth配置成功'
    }
  } else {
    // 如果没有找到配置，返回默认配置
    const defaultConfig = createDefaultOAuthConfig(providerId, `服务商${providerId}`)
    return {
      success: true,
      data: defaultConfig,
      message: '获取默认OAuth配置成功'
    }
  }
}

// 保存服务商OAuth配置
export async function mockSaveProviderOAuthConfig(config: ServiceProviderOAuthConfig): Promise<{
  success: boolean
  data: ServiceProviderOAuthConfig
  message: string
}> {
  await delay(800)

  // 模拟保存逻辑
  const existingIndex = mockOAuthConfigs.findIndex(c => c.providerId === config.providerId)

  if (existingIndex >= 0) {
    // 更新现有配置
    config.updatedTime = new Date().toLocaleString()
    mockOAuthConfigs[existingIndex] = { ...config }
  } else {
    // 新增配置
    config.id = `OAUTH_${Date.now()}`
    config.createdTime = new Date().toLocaleString()
    config.updatedTime = new Date().toLocaleString()
    mockOAuthConfigs.push(config)
  }

  return {
    success: true,
    data: config,
    message: '保存OAuth配置成功'
  }
}

// 测试OAuth配置连接
export async function mockTestOAuthConnection(
  providerId: string,
  platform: 'WXPAY' | 'ALIPAY',
  configType: string
): Promise<{
  success: boolean
  message: string
  data?: any
}> {
  await delay(1000)

  // 模拟测试逻辑
  const config = mockOAuthConfigs.find(c => c.providerId === providerId)

  if (!config) {
    return {
      success: false,
      message: '未找到OAuth配置'
    }
  }

  // 模拟不同的测试结果
  const random = Math.random()

  if (random > 0.8) {
    return {
      success: false,
      message: '连接测试失败：配置参数错误'
    }
  } else if (random > 0.6) {
    return {
      success: false,
      message: '连接测试失败：网络超时'
    }
  } else {
    return {
      success: true,
      message: '连接测试成功',
      data: {
        platform,
        configType,
        testTime: new Date().toLocaleString(),
        responseTime: Math.floor(Math.random() * 500) + 100
      }
    }
  }
}

// 获取OAuth授权URL
export async function mockGetOAuthAuthUrl(
  providerId: string,
  platform: 'WXPAY' | 'ALIPAY',
  configType: string,
  redirectUri: string
): Promise<{
  success: boolean
  data?: { authUrl: string }
  message: string
}> {
  await delay(300)

  const config = mockOAuthConfigs.find(c => c.providerId === providerId)

  if (!config) {
    return {
      success: false,
      message: '未找到OAuth配置'
    }
  }

  let authUrl = ''

  if (platform === 'WXPAY') {
    if (configType === 'MP') {
      authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${config.wechatOAuth.mp.appId}&redirect_uri=${encodeURIComponent(redirectUri)}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
    } else if (configType === 'MINIAPP') {
      authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${config.wechatOAuth.miniapp.appId}&redirect_uri=${encodeURIComponent(redirectUri)}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
    } else if (configType === 'OPEN') {
      authUrl = `https://open.weixin.qq.com/connect/qrconnect?appid=${config.wechatOAuth.open?.appId}&redirect_uri=${encodeURIComponent(redirectUri)}&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect`
    }
  } else if (platform === 'ALIPAY') {
    authUrl = `https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=${config.alipayOAuth.app.appId}&scope=${config.alipayOAuth.oauth.scope.join(',')}&redirect_uri=${encodeURIComponent(redirectUri)}&state=STATE`
  }

  return {
    success: true,
    data: { authUrl },
    message: '获取授权URL成功'
  }
}

export { mockOAuthConfigs }